<template>
  <div>
    <!--羊只称重-查询 -->
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="称重日期">
        <el-date-picker v-model="form.sDate" type="date" value-format="YYYY-MM-DD" clearable />-
        <el-date-picker v-model="form.eDate" type="date" value-format="YYYY-MM-DD" clearable />
      </el-form-item>
      <el-form-item label="羊只耳号">
        <!-- <el-input v-model="form.Earbugles" placeholder="羊只耳号" clearable /> -->
        <el-select v-model="form.Earbugles" style="width: 220px" clearable>
          <el-option label="全部" :value="0"></el-option>
          <el-option v-for="item in ear" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="称重类型">
        <el-select v-model="form.WeightType" clearable>
          <el-option label="全部" :value="0"></el-option>
          <el-option v-for="item in WeightTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="GetSheepInfo">查询</el-button>
        <el-button>重置</el-button>
      </el-form-item>
      <br />
      <el-form-item label="品&nbsp;&nbsp;&nbsp;&nbsp;种">
        <el-select v-model="form.Breed" clearable>
          <el-option label="全部" :value="0"></el-option>
          <el-option v-for="item in BreedList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="性&nbsp;&nbsp;&nbsp;&nbsp;别">
        <el-select v-model="form.Sex" clearable>
          <el-option label="全部" :value="0"></el-option>
          <el-option v-for="item in SexList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="称重月龄">
        <el-input v-model="form.EWeighMonth" clearable />-
        <el-input v-model="form.SWeighMonth" clearable />
      </el-form-item>
    </el-form>
    <el-divider />
    <el-button type="danger" @click="dialogFormVisible = true">新增</el-button>
    <el-button type="danger" @click="BatchDel()">删除</el-button>
    <!-- <el-button type="success" @click="derive">导出</el-button> -->
    <br />
    <br />
    <div v-if="TagBool">
      <el-tag style="width:1920px;color: black;height: 50px;" type="danger" :iocn="Delete">
        <spna style="font-size: 15px">
          <Warning style="width: 1em; height: 1em; margin-right: 8px" color="red" />
          <span style="margin-right: 1800px">已选择 {{ TagCount }} 项</span>
        </spna>
      </el-tag>
    </div>
    <div v-else>
      <el-tag style="width:1920px;color: black;height: 50px;" type="success" :iocn="Delete">
        <spna style="font-size: 15px">
          <SuccessFilled style="width: 1em; height: 1em; margin-right: 8px" color="green" />
          <span style="margin-right: 1800px">已选择 {{ TagCount }} 项</span>
        </spna>
      </el-tag>
    </div>
    <br />
    <!--羊只称重-列表 -->
    <el-table :data="SheepWeightList" stripe style="width: 100%" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"   />
      <el-table-column label="序号" :fixed="true" width="110px">
        <template v-slot="a">
          <span>{{ a.$index + (page.pageIndex - 1) * page.pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="WeighDate" label="称重日期" width="110px">
        <template v-slot="scope">
          <span>{{
      scope.row.WeighDate
        ? scope.row.WeighDate.replace("T", " ").substring(0, 10)
        : null
    }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="Earbugles" label="耳号" width="110px" />
      <el-table-column prop="Breed" label="品种" width="110px">
        <template v-slot="data">
          <span v-if="data.row.Breed == 1">杜泊</span>
          <span v-else-if="data.row.Breed == 2">澳洲白 </span>
          <span v-else-if="data.row.Breed == 3">萨福克</span>
          <span v-else-if="data.row.Breed == 4">杜湖</span>
          <span v-else-if="data.row.Breed == 5">杜杜湖</span>
          <span v-else-if="data.row.Breed == 6">萨杜湖</span>
          <span v-else-if="data.row.Breed == 7">澳湖</span>
          <span v-else-if="data.row.Breed == 8">湖羊</span>
          <span v-else>澳杜湖</span>
        </template>
      </el-table-column>
      <el-table-column prop="Sex" label="性别" width="110px">
        <template v-slot="data">
          <span v-if="data.row.Sex == 1">公</span>
          <span v-else>母</span>
        </template>
      </el-table-column>
      <el-table-column prop="WeightType" label="称重类型" width="110px">
        <template v-slot="data">
          <span v-if="data.row.WeightType == 1">断奶重 </span>
          <span v-else-if="data.row.WeightType == 2">月龄重 </span>
          <span v-else>出生重</span>
        </template>
      </el-table-column>
      <el-table-column prop="WeightKg" label="重量(公斤)" width="110px"/>
      <el-table-column prop="WeighMonth" label="称重月龄" width="110px"/>
      <el-table-column prop="CreateBy" label="创建人" width="110px"/>
      <el-table-column prop="CreateDate" label="创建时间" width="110px">
        <template v-slot="scope">
          <span>{{
      scope.row.CreateDate
        ? scope.row.CreateDate.replace("T", " ").substring(0, 10)
        : null
    }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="UpdateBy" label="修改人"  width="110px"/>
      <el-table-column prop="UpdateDate" label="修改时间" width="110px">
        <template v-slot="scope">
          <span>{{
      scope.row.UpdateDate
        ? scope.row.UpdateDate.replace("T", " ").substring(0, 10)
        : null
    }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right"  label="操作" width="110px">
        <template v-slot="scope">
          <el-link type="primary" @click="Del(scope.row.SwID)">删除</el-link>&nbsp;
          <el-link type="primary" @click="dialogFormVisible1 = true, EditSheepInfo(scope.row.SwID)">修改</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
        :page-sizes="[10, 20, 30, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 新增弹出层 -->
    <el-dialog v-model="dialogFormVisible" title="基本信息" width="60%" align-center>
      <el-form-item :label-width="formLabelWidth">
        <el-button type="danger" @click="AddSheepWeight(Isruleform)">新增</el-button>
        <el-button type="danger" disabled>保存</el-button>
        <el-button type="danger" disabled>撤销</el-button>
        <el-button type="danger" disabled>删除</el-button>
      </el-form-item>
      <el-form :model="Isform" ref="Isruleform" style="max-width: 600px" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="称重日期:" prop="WeighDate" :label-width="formLabelWidth">
          <el-date-picker v-model="Isform.WeighDate" type="date" style="width: 60%" value-format="YYYY-MM-DD"
            clearable />
        </el-form-item>
        <el-form-item label="羊只耳号" prop="Earbugles" :label-width="formLabelWidth">
          <el-select v-model="Isform.Earbugles" style="width: 60%" clearable @change="EditEar">
           <el-option
                v-for="item in ear"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="称重类型" prop="WeightType" :label-width="formLabelWidth">
          <el-select v-model="Isform.WeightType" style="width: 60%" clearable>
            <el-option v-for="item in WeightTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="重量(公斤)" prop="WeightKg" :label-width="formLabelWidth">
          <el-input v-model="Isform.WeightKg" style="width: 60%" clearable />
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改弹出层 -->
    <el-dialog v-model="dialogFormVisible1" title="基本信息" width="60%" align-center>
      <el-form :model="Isform1" ref="Isruleform1" style="max-width: 600px" :rules="rules1" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item :label-width="formLabelWidth">
          <el-button type="danger" disabled>新增</el-button>
          <el-button type="danger" @click="UpdSheepWeight(Isruleform1)">保存</el-button>
          <el-button type="danger" disabled>撤销</el-button>
          <el-button type="danger" disabled>删除</el-button>
        </el-form-item>
        <el-form-item label="称重日期:" prop="WeighDate" :label-width="formLabelWidth">
          <el-date-picker v-model="Isform1.WeighDate" type="date" style="width: 60%" value-format="YYYY-MM-DD"
            clearable />
        </el-form-item>
        <el-form-item label="羊只耳号" prop="Earbugles" :label-width="formLabelWidth">
          <el-select v-model="Isform1.Earbugles" style="width: 60%" clearable @change="EditEarEdit">
            <el-option v-for="item in ear" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="称重类型" prop="WeightType" :label-width="formLabelWidth">
          <el-select v-model="Isform1.WeightType" style="width: 60%" clearable>
            <el-option v-for="item in WeightTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="重量(公斤)" prop="WeightKg" :label-width="formLabelWidth">
          <el-input v-model="Isform1.WeightKg" style="width: 60%" clearable />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import http from '@/http'
import { ref, reactive, inject, onMounted } from "vue";
import type { AxiosStatic } from "axios";
import { get } from "@vueuse/core";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Delete, DocumentChecked, Back, Warning, SuccessFilled } from '@element-plus/icons-vue'
const axios = inject("axios") as AxiosStatic;
const refs = ref([
  { SwID: "" }
])


//导出 val: refs | any
const derive = () => {
  //要导出的数组数据
  const data = [
    ['姓名', '年龄'],
    ['小明', 20],
    ['小红', 22],
    ['小华', 21]
  ];
  // 创建一个新的 Workbook
  const wb = XLSX.utils.book_new();
  // 将数据转换为 worksheet
  const ws = XLSX.utils.aoa_to_sheet(data);
  // 向 Workbook 中添加 worksheet
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成 Excel 文件
  XLSX.writeFile(wb, '羊只称重列表.xlsx');
}


const EditEar = () => {
  http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + Isform.Earbugles)
  .then(res=>{
    Isform.Earbugles = res.data.earNumber;
    Isform.Breed = res.data.breed;
    Isform.Sex = res.data.sex;
  })
}

const EditEarEdit = () => {
  http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + Isform1.Earbugles)
  .then(res=>{
    Isform1.Earbugles = res.data.earNumber;
    Isform1.Breed = res.data.breed;
    Isform1.Sex = res.data.sex;
  })
}
//羊只称重列表
const SheepWeightList = ref([]);
//查询form
const form = reactive({
  eDate: "",
  sDate: "",
  Earbugles: "",
  WeightType: "" || null,
  Breed: "" || null,
  Sex: "" || null,
  EWeighMonth: "",
  SWeighMonth: "",
});

//耳号
const ear = ref()
//耳号下拉框
const earlist = () => {
  http.get("MYroute/api/SheepFile/SheepFileConditionEard").then(res => {
    ear.value = res.data;
  })
}

//品种下拉框
const BreedList = ref([
  {
    value: "",
    name: "",
  },
]);
//羊只类型下拉框
const WeightTypeList = ref([
  {
    value: "",
    name: "",
  },
]);
//性别下拉框
const SexList = ref([
  {
    value: "",
    name: "",
  },
]);
//分页属性
const page = {
  pageIndex: 1,
  pageSize: 10,
  pageCount: 0,
  totalCount: 0,
};
//总页数
const handleSizeChange = (val: number) => {
  page.pageSize = val;
  GetSheepInfo();
};
//总条数
const handleCurrentChange = (val: number) => {
  page.pageIndex = val;
  GetSheepInfo();
};
const GetWeightType = () => {
  http.get("srout/api/Breeding/GetWeightType").then((res) => {
    WeightTypeList.value = res.data;
  });
};
const GetSex = () => {
  http.get("srout/api/Breeding/GetSex").then((res) => {
    SexList.value = res.data;
  });
};
const GetBreed = () => {
  http.get("srout/api/Breeding/GetBreed").then((res) => {
    BreedList.value = res.data;
  });
};
//羊只称重列表
const GetSheepInfo = () => {
  http
    .get("srout/api/Breeding/GetSheepWeigh", {
      params: {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        Edate: form.eDate,
        Sdate: form.sDate,
        Earbugles: form.Earbugles || null,
        WeightType: form.WeightType || null,
        Breed: form.Breed || null,
        Sex: form.Sex || null,
        EWeighMonth: form.EWeighMonth,
        SWeighMonth: form.SWeighMonth,
      },
    })
    .then((res) => {
      //console.log(res.data.Result.Datas);
      SheepWeightList.value = res.data.datas;
      page.totalCount = res.data.totalCount;
      page.pageCount = res.data.pageCount;
    });
};

//新增弹出层
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const formSize = ref<ComponentSize>("default");
const Isruleform = ref<FormInstance>();
interface RuleForm {
  WeighDate: string;
  Earbugles: string;
  Breed: number,
  Sex:number,
  WeightType: string;
  WeightKg: string;
}
//新增form
const Isform = reactive<RuleForm>({
  WeighDate: "",
  Earbugles: "",
  WeightType: "",
  WeightKg: "",
  Breed: 0,
  Sex:0
});
//校验
const rules = reactive<FormRules<RuleForm>>({
  WeighDate: [
    {
      type: "date",
      required: true,
      message: "称重日期不能为空",
      trigger: "change",
    },
  ],
  Earbugles: [{ required: true, message: "羊只耳号不能为空", trigger: "blur" }],
  WeightType: [
    { required: true, message: "请选择称重类型", trigger: "change" },
  ],
  WeightKg: [
    { required: true, message: "重量(公斤)不能为空", trigger: "blur" },
  ],
});
//新增
const AddSheepWeight = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      http.post("first/api/Breeding/AddSheepWeigh", Isform).then((res) => {
        if (res.data > 0) {
          ElMessage({
            message: "羊只称重保存成功",
            type: "success",
          });
          dialogFormVisible.value = false;
          GetSheepInfo();
          formEl.resetFields();
        } else {
          ElMessage({
            message: "羊只称重保存失败",
            type: "error",
          });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//修改弹出层
const dialogFormVisible1 = ref(false)
const Isruleform1 = ref<FormInstance>();
interface UpdRuleForm {
  SwID: number,
  WeighDate: string;
  Earbugles: string;
  WeightType: string;
  WeightKg: string;
  Breed: number,
  Sex: number,
  CreateBy: string,
  CreateDate: string,
  WeighMonth: number,
}
//修改form
const Isform1 = reactive<UpdRuleForm>({
  SwID: 0,
  WeighDate: "",
  Earbugles: "",
  WeightType: "",
  WeightKg: "",
  Breed: 0,
  Sex: 0,
  CreateBy: "",
  CreateDate: "",
  WeighMonth: 0,
});
//反填
const EditSheepInfo = (SwID: any) => {
  dialogFormVisible1.value = true;
  http.get("srout/api/Breeding/EditSheepWeight?SwID=" + SwID).then((res) => {
    Isform1.Earbugles = res.data.Earbugles;
    Isform1.SwID = res.data.SwID;
    Isform1.WeighDate = res.data.WeighDate;
    Isform1.WeightType = res.data.WeightType;
    Isform1.WeightKg = res.data.WeightKg;
    Isform1.Breed = res.data.Breed;
    Isform1.Sex = res.data.Sex;
    Isform1.CreateBy = res.data.CreateBy;
    Isform1.CreateDate = res.data.CreateDate;
    Isform1.WeighMonth = res.data.WeighMonth;
  });
}
//校验
const rules1 = reactive<FormRules<UpdRuleForm>>({
  WeighDate: [
    {
      type: "date",
      required: true,
      message: "称重日期不能为空",
      trigger: "change",
    },
  ],
  Earbugles: [{ required: true, message: "羊只耳号不能为空", trigger: "blur" }],
  WeightType: [
    { required: true, message: "请选择称重类型", trigger: "change" },
  ],
  WeightKg: [
    { required: true, message: "重量(公斤)不能为空", trigger: "blur" },
  ],
});
//修改
const UpdSheepWeight = async (formEl: FormInstance | undefined) => {
  console.log(Isform1);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {

      http.post("first/api/Breeding/UpdSheepWeight", Isform1).then((res) => {
        if (res.data > 0) {
          ElMessage({
            message: "羊只称重修改成功",
            type: "success",
          });
          GetSheepInfo();
          dialogFormVisible1.value = false
        } else {
          ElMessage({
            message: "羊只称重修改失败",
            type: "error",
          });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//单个删除
const Del = (SwID: any) => {
  ElMessageBox.confirm("确定要此数据删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      http
        .delete("first/api/Breeding/DelSheepWeight?SwID=" + SwID)
        .then((res) => {
          if (res.data > 0) {
            ElMessage({
              type: "success",
              message: "信息删除成功",
            });
            GetSheepInfo();
          } else {
            ElMessage({
              type: "error",
              message: "信息删除失败",
            });
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

//批量删除
const BatchDel = () => {
  let idss = refs.value.map(x => x.SwID);
  if (refs.value.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  ElMessageBox.confirm("确定要此数据删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      http
        .post("first/api/Breeding/BatchSheepWeight?Array=" + idss)
        .then((res) => {
          if (res.data > 0) {
            ElMessage({
              type: "success",
              message: "信息批量删除成功",
            });
            GetSheepInfo();
          } else {
            ElMessage({
              type: "error",
              message: "信息批量删除失败",
            });
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });

}

//选中数据
let ids = "";
const TagBool = ref(true);
const TagCount = ref(0);
const handleSelectionChange = (val: refs | any) => {
  refs.value = val;
  ids = "";
  val.forEach(x => {
    ids += x.SwID + ",";
  })
  ids = ids.substring(0, ids.length - 1);
  TagCount.value = ids.split(',').length;
  if (ids == "") {
    TagCount.value = 0;
  }
  if (TagCount.value == 0) {
    TagBool.value = true;
  }
  else {
    TagBool.value = false;
  }
}


//钩子函数------------------------------------------------------------------------------------
onMounted(() => {
  GetSheepInfo();
  earlist();
  GetWeightType();
  GetSex();
  GetBreed();
});
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>